package com.learn.xiaoha.beanregister;

import com.alibaba.druid.pool.DruidDataSource;
import com.learn.xiaoha.ProxyMapper.ProxyMapper;
import com.learn.xiaoha.SimpleFactoryBean.SimpleFactoryBean;
import com.learn.xiaoha.annotation.SimpleScan;
import com.learn.xiaoha.sqlsession.SqlSession;
import com.learn.xiaoha.sqlsession.factory.SimpleSqlSessionFactory;
import com.learn.xiaoha.unit.ClazzUtils;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;

import java.util.List;

/**
 * SimpleBeanDefinitionRegister
 *
 * @author: cyx_jay
 * @date: 2021/2/3 17:09
 */
public class SimpleBeanDefinitionRegister implements ImportBeanDefinitionRegistrar {


    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        //获取到注解
        MultiValueMap<String, Object> myScanProperties = importingClassMetadata.getAllAnnotationAttributes(SimpleScan.class.getName());
        List<Object> value = myScanProperties.get("value");
        String packName = (String) value.get(0);
        //实例化sqlSession工厂
        //实例化数据源
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl("jdbc:mysql://127.0.0.1/vhr?serverTimezone=UTC");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("cyx520slm");
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        SimpleSqlSessionFactory simpleSqlSessionFactory = new SimpleSqlSessionFactory();
        simpleSqlSessionFactory.build(druidDataSource).build(packName);
        //包扫描
        List<String> clazzNames = ClazzUtils.getClazzName(packName, false);

        if (!CollectionUtils.isEmpty(clazzNames)){
            for (String clazzName : clazzNames) {
                try {
                    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(SimpleFactoryBean.class);
                    beanDefinitionBuilder.addPropertyValue("aClass",Class.forName(clazzName));
                    AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
                    registry.registerBeanDefinition(clazzName,beanDefinition);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
